from typing import List

from fastapi import APIRouter, Request
from fastapi import Depends
from flask import jsonify

from config.get_db import get_db
from module_admin.entity.vo.cms_order_approve_vo import OrderModelForApprove
from module_admin.entity.vo.cms_order_bill_vo import OrderBillModelForUpdate
from module_admin.entity.vo.cms_order_dispatch_vo import OrderDispatchModelForCreate, OrderDetails
from module_admin.entity.vo.cms_order_vo import OrderModel, OrderPageObject, OrderModelForQuery, \
    OrderModelForDispatchUrgent, OrderModelForExpectedMileage
from module_admin.entity.vo.data_vo import BillFile, BillFileData
from module_admin.entity.vo.user_vo import CurrentUserInfoServiceResponse, CasdoorUser
from module_admin.export.ExportPdf import ExportPdfService
from module_admin.service.cms_order_approve_service import CmsOrderApproveService
from module_admin.service.cms_order_bill_service import CmsOrderBillService
from module_admin.service.cms_order_dispatch_service import CmsOrderDispatchService
from module_admin.service.cms_order_service import CmsOrderService
from module_admin.dao.dept_dao import *
from module_admin.service.login_service import get_current_user, get_current_user_details
from utils.page_util import get_page_obj, get_new_page_obj
from utils.response_util import *
from utils.log_util import *
from utils.time_format_util import object_format_datetime

dispatchController = APIRouter(
    dependencies=[Depends(get_current_user_details)]
)


@dispatchController.post("/task/create", response_model=OrderModel, summary="创建用车申请")
async def create_order(request: Request, dept_query: OrderModel, query_db: Session = Depends(get_db),
                       current_user: CasdoorUser = Depends(get_current_user_details)):
    try:
        dept_query.create_by = current_user.name
        dept_query.update_by = current_user.name
        dept_query_result = CmsOrderService.create_order(query_db, dept_query)
        return response_200(data=dept_query_result, message="新增成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.get("/task/delete/{order_id}")
async def delete_order(request: Request, order_id: int, query_db: Session = Depends(get_db)):
    try:
        dept_query_result = CmsOrderService.delete_order(query_db, order_id)
        return response_200(data=dept_query_result, message="删除成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/task/update")
async def update_order(request: Request, order_update: OrderModel, db: Session = Depends(get_db)):
    try:
        dept_query_result = CmsOrderService.update_order(db, order_update)
        return response_200(data=dept_query_result, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))

    # expected_mileage


@dispatchController.post("/task/expected_mileage", summary="预计里程-计算接口")
async def expected_mileage(request: Request, order_model_for_expected_mileage: OrderModelForExpectedMileage,
                           query_db: Session = Depends(get_db)):
    try:
        return response_200(data=100, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.get("/task/get/{id}")
async def get_order(request: Request, id: int, query_db: Session = Depends(get_db)):
    try:
        dept_query_result = CmsOrderService.get_order(query_db, id)
        object_format_datetime(dept_query_result)
        return response_200(data=dept_query_result, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/task/page",
                         summary="工作台-待办任务(card_state:(用车审批,车辆调度,任务进行中))/驾驶员待办任务-待办任务(state:(4,5,6))")
async def page_order(request: Request, order_page_query: OrderPageObject, db: Session = Depends(get_db)):
    try:
        # query_object = OrderModelForQuery(**order_page_query.dict())
        page_result = CmsOrderService.page(db, order_page_query)
        total = CmsOrderService.count(db, order_page_query)
        list_format_datetime(page_result)
        # 分页操作
        page_result_after = get_new_page_obj(page_result, order_page_query.page_num, order_page_query.page_size, total)
        # 处理
        return response_200(data=page_result_after, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/taskall/page",
                         summary="工作台-运单记录(state默认传:7，bill_state默认传:未结算)/工作台-全部记录")
async def page_order(request: Request, order_page_query: OrderPageObject, db: Session = Depends(get_db)):
    try:
        # query_object = OrderModelForQuery(**order_page_query.dict())
        page_result = CmsOrderService.page2(db, order_page_query)
        total = CmsOrderService.count2(db, order_page_query)
        list_format_datetime(page_result)
        # 分页操作
        page_result_after = get_new_page_obj(page_result, order_page_query.page_num, order_page_query.page_size, total)
        # 处理
        return response_200(data=page_result_after, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/task/approve", summary="用车审批", description="用车审批")
async def approve(request: Request, order_request: OrderModelForApprove, db: Session = Depends(get_db),
                  current_user: CasdoorUser = Depends(get_current_user_details)):
    try:
        CmsOrderApproveService.pass_or_refuse(db, order_request, current_user)
        # 处理
        return response_200(data=None, message="成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/task/dispatch", summary="车辆调度")
async def dispatch(request: Request, order_request: OrderDispatchModelForCreate, db: Session = Depends(get_db),
                   current_user: CasdoorUser = Depends(get_current_user_details)):
    try:
        CmsOrderDispatchService.dispatch(db, order_request, current_user)
        # 处理
        return response_200(data=None, message="成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.get("/task/dispatch/{id}", summary="取消流程 id为用车申请数字id")
async def dispatch(request: Request, order_id: int, db: Session = Depends(get_db)):
    try:
        CmsOrderDispatchService.cancel(db, order_id)
        # 处理
        return response_200(data=None, message="成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/task/dispatch/urgent", summary="应急调度")
async def dispatch_urgent(request: Request, order_request: OrderModelForDispatchUrgent, db: Session = Depends(get_db),
                          current_user: CasdoorUser = Depends(get_current_user_details)):
    try:
        CmsOrderDispatchService.dispatch_urgent(db, order_request, current_user)
        # 处理
        return response_200(data=None, message="成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.get("/order/detail/{id}", response_model=OrderDetails,
                        summary="工作台-（代办任务-运单记录详情，全部记录-运单记录详情），"
                                "驾驶员待办任务-待办任务-全部记录-运单记录详情,"
                                "财务-运单结算-运单结算详情")
async def confirm_detail(request: Request, id: int,
                         query_db: Session = Depends(get_db)):
    try:
        dept_query_result = CmsOrderService.detail(query_db, id)
        return response_200(data=dept_query_result, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/task/updateMileage", summary="修改里程")
async def update_order(request: Request, order_update: OrderBillModelForUpdate, db: Session = Depends(get_db)):
    try:
        dept_query_result = CmsOrderBillService.update_mileage(db, order_update)
        return response_200(data=dept_query_result, message="获得成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dispatchController.post("/get", summary="文件导出 ord_2406270001064431格式的id")
async def get(request: Request, order_id_str_list: List[str], query_db: Session = Depends(get_db)):
    try:
        return_list = []
        for order_id_str in order_id_str_list:
            data: BillFileData = CmsOrderBillService.get_export_data(query_db, order_id_str)
            base64_file = ExportPdfService.export_and_get_base64(data)
            file = BillFile()
            file.order_id = order_id_str
            file.base64_file = base64_file
            return_list.append(file)
        return response_200(data=return_list, message="")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))
